import { PureComponent } from "react";
import { Button, Modal,ActivityIndicator,InputItem,Tabs,SearchBar,Carousel,PullToRefresh,ListView } from "antd-mobile"
import { connect } from 'dva';
import { handleImg, goToPage,isNull,handleOSS } from "../../utils/helper";
import MToast from '../../components/Util/MToast';
import {IntlProvider, addLocaleData,FormattedMessage} from 'react-intl';
import localeData from '../../../public/lang/data.json';
import { Row, Col } from 'antd';
import ReactDOM from 'react-dom';
import Macy from 'macy';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
@connect(() => {
  return ({

  })
})
export default class categoryPage4 extends PureComponent{
  constructor(props){
    super(props);

    this.state = {

      TabData:[],
      TabDataList:[],
      aa:[],
      goodsItem:[],
      hasMore: true,
      refreshing: true,
      isLoading: true,
      height: document.documentElement.clientHeight,
      useBodyScroll: false,
      onSearch:false,
      IsImage:false,
      masonry:false,
      data:[],
      leftData:[],
      rightData:[],
      loading:true,
      noLogin:false,

    }
  }
  componentDidUpdate() {

  }
  componentDidMount() {
    const hei = this.state.height - 261;
    console.log(this.state.height)
    setTimeout(() => {
      this.setState({
        height: hei,

      });
    }, 0);
    let {dispatch,location} = this.props;
    console.log(location.search)
    const query = location.search;
    console.log(query)
    const arr = query.split('&') // ['?s=', 'f=7']
    const code = arr[0].substr(6) // '1'
    localStorage.setItem("code",code)
    const name = arr[1].substr(5) // '7'
    console.log(code,decodeURI(name))
    this.handleGoodsList(code);
  }
  componentWillMount(){
    let {dispatch,location} = this.props;
    console.log(location.search)
    const query = location.search;
    console.log(query)
    const arr = query.split('&') // ['?s=', 'f=7']
    const code = arr[0].substr(6) // '1'
    localStorage.setItem("code",code)
    const name = arr[1].substr(5) // '7'
    console.log(code,decodeURI(name))
    dispatch({
      type: "global/setHeaderTitle",
      payload: {
        title: decodeURI(name),
        path: location.pathname + location.search
      }
    });
  this.handleCategoryList(code);
    if(	localStorage[MI_APP_CODE + "phone"]==undefined){
      this.setState({
        noLogin:false
      })
    }else{
      this.setState({
        noLogin:true
      })
    }

  }
  handleCategoryList=(code)=>{
    let {dispatch,location} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/all?_c=new_category_list_show_node",
          params: [
            {
              "key":"parent_id",
              "value":code
            }
          ],
          _c: "new_category_list_show_node"
        },
        callback: (result) => {
          let { data } = result;


          var result =[];
          for(var i=0;i<data.length;i+=4){
            result.push(data.slice(i,i+4))
          }
          console.log(result)
          this.setState({
            TabData:data,
            TabDataList:result,
            loading:false
          })

        }
      }
    });
  }
  getHW(data){
    let heightDate = [0,0];//接收累计高度的容器数组
    let rightData =[]//渲染右侧盒子的数组
    let leftData = []//渲染左侧盒子的数组
    data.forEach(item => {
      let height = 1;//对url地址进行一个截取，拿到高度
      let minNum = Math.min.apply(null,heightDate)// 从heighetData筛选最小项
      console.log(minNum)
      let minIndex = heightDate.indexOf(minNum);// 获取 最小项的小标 准备开始进行累加
      console.log(minIndex)
      heightDate[minIndex] = heightDate[minIndex] + height;//从 heightData 中找到最小的项后进行累加，
      if(minIndex===0){//[0]加到left [1]加到 right
        leftData.push(item)
      }else{
        rightData.push(item)
      }
    })
    this.setState({ leftData,rightData  });//重新set state
  }
  handleGoodsList=(code,pages)=>{
    let {dispatch,location} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/all?_c=app_category_goods_list_search",
          params: [
            {
              "key":"category_id",
              "value":code
            }
          ],
          _c: "app_category_goods_list_search"
        },
        callback: (result) => {
          let { data } = result;
          const len=data.length;
          this.getHW(data) //调用
          this.setState({
            goodsItem:data,
            loading:false,
          })

        }
      }
    });
}
  onRefresh = () => { //下拉刷新
    this.setState({ refreshing: true,  });
    // simulate initial Ajax
    let {dispatch,location} = this.props;
    console.log(location.search)
    const query = location.search;
    console.log(query)
    const arr = query.split('&') // ['?s=', 'f=7']
    console.log(arr)
    const code = arr[0].substr(6) // '1'
    localStorage.setItem("code",code)
    const name = arr[1].substr(5) // '7'
    console.log(code,name)

    setTimeout(() => {
      this.handleGoodsList(code);
      this.setState({ refreshing: false });
    }, 600);

  }
  // 滑动到底部时加载更多
  onEndReached = (event) => {//触底加载
    if (this.state.isLoading) {
      return;
    }
    this.setState({ isLoading: true });
    if(this.state.onSearch){
      setTimeout(() => {
        this.submit(this.state.pages);
      }, 600);
    }else{
      setTimeout(() => {
        this.handleGoodsList(localStorage.getItem("code"),this.state.pages);
      }, 600);
    }
  }
  handleCategory=(e,i)=>{
    let {dispatch} = this.props;
    goToPage({ dispatch, config: { url: "/category_page2?code="+i.id+"&name="+i.name }, isReplace: false })
  }
  categoryList(){
    let {TabDataList} = this.state;
    if (!TabDataList || TabDataList.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T(localeData[localStorage.locale].goodsDetailCartNoGood)}
        </div>
      )
    }
    else{
      return(
        <Carousel
          autoplay={false}
          infinite={false}
          dots={false}
          className="carousel"
        >

          {TabDataList.map((i,k)=>(
            <Row key={i.code}>
              {i.map((i,k)=>(
                <Col span={6} key={i.code} style={{padding:'0 2%'}} onClick={(e)=>{this.handleCategory(e,i)}}>
                  <img src={handleOSS(i.img_url)} style={{width:'100%',height:'73px'}}/>
                  <p  className="ellipsis4" style={{color:'#303133',marginTop:'10px',width:'100%'}}>{i.name}</p>
                </Col>
              ))}

            </Row>
          ))}


        </Carousel>
      )
    }
  }
  goodList() {
    let { leftData,rightData,goodsItem,IsImage} = this.state;


    if (!goodsItem || goodsItem.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T(localeData[localStorage.locale].goodsDetailCartNoGood)}
        </div>
      )
    }
    else {
      let contents = [];
      return (
        <div style={{overflow:'hidden'}}>
          <div className='left'>
            {
              leftData && leftData.map((item,index)=>{
                return     <div style={{marginBottom:'6%'}} >
                  <div  key={index} style={{background:'#fff',fontWeight:'bold',padding:'5% 5% 5%',borderRadius:'10px'}} className="item">
                    <div onClick={(e)=>{this.handleDetail(e,item)}}>
                      {IsImage?
                        <img src={handleOSS(item.img_url)} style={{width:'100%',height:'100%'}}   onLoad={this.handleImageLoaded}/>
                        :<img src="image/falls.png" style={{width:'100%',height:'100%'}}   onLoad={this.handleImageLoaded}/>}

                    </div>
                    <div style={{overflow:'hidden'}}>
                      <p className="ellipsis2" style={{margin:'12px 0px 0px',textAlign:'left',color:'#595867',fontSize:'13px',height:'35px'}}>{item.goods_name}</p>
                      <div style={{float:'left',color:'#F09600',fontSize:'15px',marginTop:'5px'}}>€{item.price}</div>
                      <div style={{float:'right',width:'34px',height:'34px'}} onClick={(e) => {this.handleAdd(e,item) }}>
                        <img src="image/cart1.png" style={{width:'32px',height:'32px'}}/>
                      </div>
                    </div>

                    {/*<Button type="primary" size="small" inline style={{marginBottom:'1em'}} onClick={(e) => {this.handleAdd(e,i) }}>+ADD</Button>*/}
                  </div>


                </div>
              })
            }
          </div>
          <div className='right'>
            {
              rightData && rightData.map((item,index)=>{
                return <div style={{marginBottom:'6%'}} >
                  <div  key={index} style={{background:'#fff',fontWeight:'bold',padding:'5% 5% 5%',borderRadius:'10px'}} className="item">
                    <div onClick={(e)=>{this.handleDetail(e,item)}}>
                      {IsImage?
                        <img src={handleOSS(item.img_url)} style={{width:'100%',height:'100%'}}   onLoad={this.handleImageLoaded}/>
                        :<img src="image/falls.png" style={{width:'100%',height:'100%'}}   onLoad={this.handleImageLoaded}/>}

                    </div>
                    <div style={{overflow:'hidden'}}>
                      <p className="ellipsis2" style={{margin:'12px 0px 0px',textAlign:'left',color:'#595867',fontSize:'13px',height:'35px'}}>{item.goods_name}</p>
                      <div style={{float:'left',color:'#F09600',fontSize:'15px',marginTop:'5px'}}>€{item.price}</div>
                      <div style={{float:'right',width:'34px',height:'34px'}} onClick={(e) => {this.handleAdd(e,item) }}>
                        <img src="image/cart1.png" style={{width:'32px',height:'32px'}}/>
                      </div>
                    </div>

                    {/*<Button type="primary" size="small" inline style={{marginBottom:'1em'}} onClick={(e) => {this.handleAdd(e,i) }}>+ADD</Button>*/}
                  </div>


                </div>
              })
            }
          </div>
        </div>

      )
    }
  }
  onChange= (value) => {
    this.setState({ value });
  };
  submit=(pages)=>{
    let {dispatch,location} = this.props;
    let {value,loading,leftData,rightData} = this.state;
    this.setState({
      leftData:[],
      rightData:[]
    })
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/all?_c=app_search_goods_list",
          params: [
            {
              key: "keyword",
              value: value
            },
          ],
          _c: "app_search_goods_list"
        },
        callback: (result) => {
          let { data } = result;
          let {loading} = this.state;
          if(data==''){
            MToast.info(T(localeData[localStorage.locale].goodsDetailCartNoGood),1, null, false);
          }else{

          }
          this.getHW(data) //调用

        }
      }
    });
  }
  handleDetail=(e,i)=>{
    let {dispatch} = this.props;
    goToPage({ dispatch, config: { url: "/goodsDetail?id="+i.id+"&store_id="+i.store_id+"&status="+i.status }, isReplace: false })
  }
  handleAdd=(e,i)=>{
    // console.log(i);
    let {dispatch} = this.props;
    if(	localStorage[MI_APP_CODE + "phone"]==undefined){
      goToPage({ dispatch, config: { url: "/newLogin" }, isReplace: false })
      // MToast.info(T("您还未登录，请登录后操作",3, null, false));
    }else{
      dispatch({
        type: "form/query",
        payload: {
          apiInfo: {
            url: "cart/add",
            params: [
              {
                key: "goods_id",
                value: i.id
              },
              {
                key: "goods_name",
                value: i.goods_name
              },
              {
                key: "img_url",
                value: i.img_url?i.img_url:' '
              },
              {
                key: "price",
                value: i.price
              },
              {
                key: "quantity",
                value: 1
              }
            ]
          },
          callback: (result) => {
            let { data } = result;
            console.log(data)
            if(data.status=="0"){
              MToast.info(T(localeData[localStorage.locale].goodSold),1, null, false);
            }else{
              MToast.info(T(localeData[localStorage.locale].goodsDetailCartInfo),1, null, false);
            }


          }
        }
      })
    }

  }
  handleImageLoaded=()=>{
    let {IsImage}=this.state;
    this.setState({
      IsImage:true
    })
  }
  render(){
    let {dispatch} = this.props;
    let {TabData,TabDataList,IsImage,loading,noLogin} = this.state;
    const messages = localeData[localStorage.locale]
    if (loading) {
      return (
        <div className="normal">
          <ActivityIndicator toast text={messages.loading} animating={true} />
        </div>
      )
    }
    return(
      <IntlProvider
        locale={ localStorage.locale } messages={messages}
      >
      <div style={{background:'#F6F6FC',width:'100%',height:'100%'}}>
        <Col span={2} style={{position:'fixed',top:'3px',right:'12px',zIndex:1000}}>
          {noLogin? <img src="image/cart10.png" style={{width:'40px',height:'40px'}}   onClick={() => {
            goToPage({ dispatch, config: { url: "/goodcart" }, isReplace: false })
          }}/>:<img src="image/cart10.png" style={{width:'40px',height:'40px'}}   onClick={() => {
            goToPage({ dispatch, config: { url: "/ungoodcart" }, isReplace: false })
          }}/>}
        </Col>
        <div style={{paddingTop:'45px',}}> <SearchBar
          placeholder={messages.search}
          maxLength={200}
          onChange={this.onChange}
          onSubmit={value => this.submit(value)}
        /></div>

        <div style={{background:'#fff',padding:'10px',marginBottom:'10px'}}>
          {this.categoryList()}
        </div>
        <PullToRefresh
          damping={60}
          ref={el => this.ptr = el}
          style={{
            height: this.state.height,
            overflow: 'auto',
          }}
          refreshing={this.state.refreshing}
          onRefresh={this.onRefresh}
        >
          {this.goodList()}
        </PullToRefresh>



      </div>
      </IntlProvider>
    )
  }
}
